package dyyx.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class EchoClient {
	
	private  final Socket socket;
	
    // private final InputStream inputStream;
	
	private final BufferedReader reader;
	private final BufferedWriter writer;

    
    private static final String UTF8 = "UTF-8";

	public EchoClient(String ip,int port)throws Exception{
		this.socket = new Socket();
		
		SocketAddress socketAddress = new InetSocketAddress(ip ,port); 
		socket.connect(socketAddress,5000); 
        
        
		socket.setKeepAlive(true);
		socket.setTcpNoDelay(true);
		// socket.setSoLinger(on, linger);
		//socket.setSoTimeout(timeout);
		// socket.getInputStream();
		
		BufferedReader readertmp = new BufferedReader(new InputStreamReader(socket.getInputStream(),UTF8));
		BufferedWriter writertmp = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),UTF8));
		this.reader = readertmp;
		this.writer = writertmp;

	}
	
	public String doWriteLine(String str)throws Exception{
		writer.write(str+"\n");
		writer.flush();
		return reader.readLine();
	}
	
	public void close()throws Exception{
		CommUtil.close(reader);
		CommUtil.close(writer);
	}

	
}
